package com.OrderingServer.service.impl;

import cn.hutool.core.util.IdUtil;
import com.OrderingServer.dto.OrderDTO;
import com.OrderingServer.enum1.OrderStatusEnum;
import com.OrderingServer.enum1.PayStatusEnum;
import com.OrderingServer.enum1.ResultEnum;
import com.OrderingServer.exception.SellException;
import com.OrderingServer.pojo.OrderDetail;
import com.OrderingServer.pojo.OrderMaster;
import com.OrderingServer.mapper.OrderMasterMapper;
import com.OrderingServer.pojo.ProductInfo;
import com.OrderingServer.service.IOrderDetailService;
import com.OrderingServer.service.IOrderMasterService;
import com.OrderingServer.service.ProductInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xingo
 * @since 2025-08-13
 */
@Service
public class OrderMasterServiceImpl extends ServiceImpl<OrderMasterMapper, OrderMaster> implements IOrderMasterService {
    /**
     * 买家下单--事务操作！ @Transactional  事务注解
     * @param orderDTO
     * @return
     */
    @Autowired
    ProductInfoService productInfoService;
    @Autowired
    IOrderDetailService orderDetailService;
    @Autowired
    OrderMasterMapper orderMasterMapper;
    @Transactional
    @Override
    public OrderDTO createOrder(OrderDTO orderDTO) {
        String orderId = String.valueOf(IdUtil.getSnowflake().nextId());
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        //1. 查询商品并计算总价
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.getById(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            // 计算订单总价
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);

            // 订单详情入库
            orderDetail.setDetailId(String.valueOf(IdUtil.getSnowflake().nextId()));
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailService.save(orderDetail);
        }

        //3. 写入订单数据库
        OrderMaster orderMaster = new OrderMaster();
        // 先复制属性
        BeanUtils.copyProperties(orderDTO, orderMaster);
        // 然后覆盖重要字段
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);  // 使用计算好的金额
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());

        orderMasterMapper.insert(orderMaster);

        //4. 扣库存
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            String productId = orderDetail.getProductId();
            Integer productQuantity = orderDetail.getProductQuantity();
            ProductInfo productInfo = productInfoService.getById(productId);

            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() - productQuantity;
            if (result < 0) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);
            productInfoService.updateById(productInfo);
        }

        orderDTO.setOrderId(orderId);
        orderDTO.setOrderAmount(orderAmount);
        orderDTO.setOrderStatus(OrderStatusEnum.NEW.getCode());// 确保返回的DTO也有正确的金额
        return orderDTO;
    }
    @Override
    public PageInfo<OrderMaster> selectPage(Integer pageNum, Integer pageSize, String buyerName) {
        //设置分页插件
        PageHelper.startPage(pageNum, pageSize);
        //正常查询，查询数据
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<OrderMaster>();
        queryWrapper.like(true,"buyer_name",buyerName);
        queryWrapper.eq("del","0");//未删除
        List<OrderMaster> list = orderMasterMapper.selectList(queryWrapper);
        return PageInfo.of(list);
    }

    @Override
    public List<OrderDTO> findlist(String openid) {
        List<OrderDTO> list = new ArrayList<>();
    List<OrderMaster> orderMasters= orderMasterMapper.selectList(new QueryWrapper<OrderMaster>().eq("del",0).eq("buyer_openid",openid));
        for (OrderMaster orderMaster : orderMasters) {
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderMaster, orderDTO);
            list.add(orderDTO);
        }
        return  list;
    }

    @Override
    public OrderDTO findOrderInfo(String openid, String orderid) {
     OrderMaster orderMaster=orderMasterMapper.selectById(orderid);
      if(orderMaster==null){
          throw new SellException(ResultEnum.ORDER_NOT_EXIST);
      }
     List<OrderDetail> orderDetailList= orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id",orderid));
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderMaster, orderDTO);
            orderDTO.setOrderDetailList(orderDetailList);
            if(!orderDTO.getBuyerOpenid().equals(openid)){
                log.error("【查询订单】订单的openid不一致 openid={},orderDTO={}");
                throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
            }
            return orderDTO;
    }
    @Transactional
    @Override
    public OrderDTO buyercancel(String openid, String orderid) {
      OrderMaster orderMaster=  orderMasterMapper.selectById(orderid);
      if(orderMaster==null){
          log.error("查不到订单");
          throw new SellException(ResultEnum.ORDER_NOT_EXIST);
      }
      String openid1=orderMaster.getBuyerOpenid();
      if(!openid.equals(openid1)){
          log.error("openid不一致");
          throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
      }
      if(!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
          log.error("订单状态错误");
          throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
      }
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        int i = orderMasterMapper.updateById(orderMaster);
        if(i<0){
            log.error("订单更新失败");
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
      List<OrderDetail>  orderDetailList= orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id",orderid));
        if(orderDetailList.isEmpty()){
            log.error("该订单详情不存在");
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        for (OrderDetail orderDetail : orderDetailList) {
            ProductInfo productInfo = productInfoService.getById(orderDetail.getProductId());
            if(productInfo==null){
                log.error("此商品不存在");
             throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result=productInfo.getProductStock()+orderDetail.getProductQuantity();
            productInfo.setProductStock(result);
            productInfoService.updateById(productInfo);
        }
        return null;
    }
}
